<template>
  <div class="wangge-chart">
    <el-row :gutter="20" align="middle" style="margin-top: -16px">
      <el-col :span="12">
        <div class="wangge-chart-title">区县网格平均薪酬统计</div>
      </el-col>
      <el-col :span="6">
        <el-select
          v-model="selectedDistrict"
          placeholder="选择区县"
          style="width: 110%"
          @change="handleDistrictChange"
        >
          <el-option
            v-for="district in districtOptions"
            :key="district.value"
            :label="district.label"
            :value="district.value"
          />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="wanggeSelectedDate"
          style="width: 115%"
          type="month"
          value-format="YYYY-MM"
          format="YYYY-MM"
          placeholder="选择月份"
          :picker-options="wanggePickerOptions"
          @change="handleWanggeDateChange"
          :disabled-date="wanggeDisabledDate"
        />
      </el-col>
    </el-row>
    <div
      ref="wanggeChart"
      class="wangge-chart-container"
      style="height: 400px"
    />
  </div>
</template>

<script>
import { ElDatePicker, ElRow, ElCol, ElSelect, ElOption } from "element-plus";
import { avgWangge, monWangge } from "@/api/dwxc/salary";
import * as echarts from "echarts";

export default {
  components: {
    ElDatePicker,
    ElRow,
    ElCol,
    ElSelect,
    ElOption,
  },
  props: {
    selectedDate: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      wanggeSelectedDate: this.selectedDate,
      selectedDistrict: "浔阳区", // 选中的区县，默认选择浔阳区
      districtOptions: [
        { label: "浔阳区", value: "浔阳区" },
        { label: "濂溪区", value: "濂溪区" },
        { label: "柴桑区", value: "柴桑区" },
        { label: "瑞昌市", value: "瑞昌市" },
        { label: "共青城", value: "共青城" },
        { label: "庐山市", value: "庐山市" },
        { label: "武宁县", value: "武宁县" },
        { label: "修水县", value: "修水县" },
        { label: "永修县", value: "永修县" },
        { label: "德安县", value: "德安县" },
        { label: "都昌县", value: "都昌县" },
        { label: "湖口县", value: "湖口县" },
        { label: "彭泽县", value: "彭泽县" },
      ],
      wanggePickerOptions: {
        disabledDate: (time) => {
          const now = new Date();
          const firstDayOfMonth = new Date(
            now.getFullYear(),
            now.getMonth(),
            1
          );
          return time.getTime() >= firstDayOfMonth.getTime();
        },
      },
      wanggeData: null,
      wanggeHbData: null,
    };
  },
  mounted() {
    this.initializeChart();
  },
  watch: {
    selectedDate: {
      handler(newVal) {
        // 只有当外部传入的日期与当前日期不同时才更新
        if (newVal !== this.wanggeSelectedDate) {
          this.wanggeSelectedDate = newVal;
          this.getWanggeData(newVal);
        }
      },
      immediate: false,
    },
  },
  methods: {
    wanggeDisabledDate(time) {
      // Disable current month and future months
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth(); // 0-11

      const selectedDate = new Date(time);
      const selectedYear = selectedDate.getFullYear();
      const selectedMonth = selectedDate.getMonth(); // 0-11 // Disable if selected date is current or future month

      return (
        selectedYear > currentYear ||
        (selectedYear === currentYear && selectedMonth >= currentMonth)
      );
    },

    initializeChart() {
      // 如果有传入的日期，使用传入的日期
      if (this.wanggeSelectedDate) {
        this.getWanggeData(this.wanggeSelectedDate);
      } else {
        // 如果没有传入日期，使用上个月作为默认日期
        const now = new Date();
        const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const defaultDate =
          lastMonth.getFullYear() +
          "-" +
          String(lastMonth.getMonth() + 1).padStart(2, "0") +
          "-01";
        this.wanggeSelectedDate = defaultDate;
        this.getWanggeData(defaultDate);
      }
    },
    handleWanggeDateChange(date) {
      console.log("wanggeChart handleWanggeDateChange called with:", date);
      // 先更新本地日期，避免watch重复触发
      this.wanggeSelectedDate = date;
      this.getWanggeData(date);
      // 向父组件发送事件
      this.$emit("handle-date-change", date);
    },
    handleDistrictChange(district) {
      console.log("wanggeChart handleDistrictChange called with:", district);
      this.getWanggeData(this.wanggeSelectedDate);
    },
    async getWanggeData(time) {
      const queryTime = time || this.wanggeSelectedDate;

      if (!queryTime) {
        this.$message.warning("请先选择查询时间！");
        return;
      }

      try {
        let formattedTime = queryTime;
        if (queryTime.match(/^\d{4}-\d{2}$/)) {
          formattedTime = queryTime + "-01";
        } else if (queryTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
          formattedTime = queryTime;
        }

        // console.log('getWanggeData - 请求时间:', formattedTime);
        // console.log('getWanggeData - 选中区县:', this.selectedDistrict);

        // 构建请求参数，包含时间和区县
        const params = { time: formattedTime };
        if (this.selectedDistrict) {
          params.district = this.selectedDistrict;
        }
        console.log("getWanggeData - 请求参数:", params);
        const res = await avgWangge(params);
        const hbres = await monWangge(params);

        // console.log('getWanggeData - avgWangge响应:', res);
        // console.log('getWanggeData - monWangge响应:', hbres);

        // 处理不同的响应数据结构
        const salaryData = res.data || res; // avgWangge可能直接返回数据
        const momData = hbres.data || hbres; // monWangge包装在{code, msg, data}中

        // console.log('getSalaryData - 标准化后的薪酬数据:', salaryData);
        // console.log('getSalaryData - 标准化后的环比数据:', momData);

        if (salaryData && momData) {
          const processedData = this.processWanggeData(salaryData);
          const processedHbData = this.processWanggeHbData(momData);
          // console.log('getWanggeData - 处理后的薪酬数据:', processedData);
          // console.log('getWanggeData - 处理后的环比数据:', processedHbData);

          this.wanggeData = processedData;
          this.wanggeHbData = processedHbData;
          this.initWanggeChart(
            this.$refs.wanggeChart,
            processedData,
            processedHbData
          );
        } else {
          if (res) console.log("- res完整内容:", res);
          if (hbres) console.log("- hbres完整内容:", hbres);
          this.$message.warning("后端返回数据为空，使用默认数据显示");
          this.initWanggeChart(this.$refs.wanggeChart, null, null);
        }
      } catch (error) {
        console.error("获取薪酬统计数据失败：", error);
        this.$message.error("获取薪酬统计数据失败：" + error.message);
        this.initWanggeChart(this.$refs.wanggeChart, null, null);
      }
    },
    processWanggeData(data) {
      const categories = ["全区县"];
      const values = [];

      if (data.cityAvgSalary !== undefined && data.cityAvgSalary !== null) {
        values.push(data.cityAvgSalary);
      } else {
        values.push(0);
      }

      if (
        data.districtAvgSalaries &&
        typeof data.districtAvgSalaries === "object"
      ) {
        Object.keys(data.districtAvgSalaries).forEach((district) => {
          categories.push(district);
          values.push(data.districtAvgSalaries[district] || 0);
        });
      }

      return {
        categories: categories,
        values: values,
      };
    },
    processWanggeHbData(data) {
      const categories = ["全区县"];
      const values = [];

      if (data.cityMom !== undefined && data.cityMom !== null) {
        values.push(data.cityMom);
      } else {
        values.push(0);
      }

      if (data.salaries && typeof data.salaries === "object") {
        Object.keys(data.salaries).forEach((district) => {
          categories.push(district);
          values.push(data.salaries[district] || 0);
        });
      }

      return {
        categories: categories,
        values: values,
      };
    },
    initWanggeChart(chartRef, wanggeProcessedData, hbProcessedData) {
      if (!chartRef) return;

      if (chartRef._echarts_instance_) {
        chartRef._echarts_instance_.dispose();
      }

      const chart = echarts.init(chartRef);

      if (
        wanggeProcessedData &&
        wanggeProcessedData.categories &&
        wanggeProcessedData.values
      ) {
        chart.setOption({
          title: {
            // text: '各区县月均薪酬统计',
            // left: 'center'
          },
          grid: {
            top: "12%",
            left: "0%",
            right: "0%",
            bottom: "3%",
            containLabel: true,
            borderWidth: 0, // 去掉网格边框
            show: false, // 隐藏网格背景
          },
          xAxis: {
            type: "category",
            data: wanggeProcessedData.categories,
            axisLabel: {
              rotate: 45,
              fontSize: 12,
              fontWeight: "normal",
              color: "#6A6A6A",
              fontFamily: "Arial, sans-serif",
              formatter: function (value) {
                return value;
              },
            },
          },
          yAxis: [
            {
              type: "value",
              name: "薪酬(元)",
              min: 0,
            },
            {
              type: "value",
              name: "环比(%)",
              scale: true,
              splitLine: {
                show: true,
                lineStyle: {
                  color: ["#E6E6E6"],
                  type: "dashed",
                },
              },
              axisLine: {
                show: false, // 隐藏右侧Y轴线
                lineStyle: {
                  color: "#999",
                },
              },
              axisLabel: {
                formatter: "{value}%",
                color: "#666",
              },
              // 自动计算合适的范围，确保0%在中间
              min: function (value) {
                // 获取数据的最小值和最大值
                const dataMin = value.min;
                const dataMax = value.max;

                // 如果数据都是正数，从0开始
                if (dataMin >= 0) {
                  return 0;
                }
                // 如果数据都是负数，让最大值为0
                if (dataMax <= 0) {
                  return dataMin;
                }
                // 如果有正有负，让0在中间
                const absMax = Math.max(Math.abs(dataMin), Math.abs(dataMax));
                return -absMax;
              },
              max: function (value) {
                const dataMin = value.min;
                const dataMax = value.max;

                // 如果数据都是正数，使用数据最大值
                if (dataMin >= 0) {
                  return dataMax;
                }
                // 如果数据都是负数，最大值为0
                if (dataMax <= 0) {
                  return 0;
                }
                // 如果有正有负，让0在中间
                const absMax = Math.max(Math.abs(dataMin), Math.abs(dataMax));
                return absMax;
              },
            },
          ],
          series: [
            {
              name: "平均薪酬",
              data: wanggeProcessedData.values,
              type: "bar",
              itemStyle: {
                color: function (params) {
                  return params.dataIndex === 0 ? "#FAC858" : "#73C0DE";
                },
              },
              label: {
                show: true,
                position: "top",
                fontSize: 12,
                color: "#333",
                fontWeight: "normal",
                formatter: function (params) {
                  if (
                    params.value === 0 ||
                    params.value === null ||
                    params.value === undefined
                  ) {
                    return "";
                  }
                  return Math.round(params.value);
                },
              },
            },
            {
              name: "薪酬环比率",
              data: hbProcessedData ? hbProcessedData.values : [],
              type: "line",
              yAxisIndex: 1,
              smooth: true, // 平滑曲线
              symbol: "circle", // 数据点形状
              symbolSize: 6, // 数据点大小
              lineStyle: {
                width: 2,
                color: "#FAC858",
              },
              itemStyle: {
                color: function (params) {
                  // 根据数值正负设置不同颜色
                  return params.value >= 0 ? "#FF4500" : "#3BA272";
                },
                borderColor: "#fff",
                borderWidth: 2,
              },
              label: {
                show: false,
                position: function (params) {
                  // 负数标签显示在下方，正数显示在上方
                  return params.value >= 0 ? "top" : "bottom";
                },
                fontSize: 11,
                color: function (params) {
                  return params.value >= 0 ? "#FF4500" : "#FAC858";
                },
                fontWeight: "bold",
                formatter: function (params) {
                  if (params.value === 0) {
                    return "0%";
                  }
                  return (
                    (params.value > 0 ? "+" : "") +
                    params.value.toFixed(1) +
                    "%"
                  );
                },
              },
              markLine: {
                silent: true,
                symbol: "none",
                label: {
                  show: false,
                },
                data: [
                  {
                    yAxis: 0,
                    lineStyle: {
                      color: "rgba(51, 51, 51, 0.5)", // 使用rgba设置透明度，0.8表示80%不透明度
                      type: "solid",
                      //   width: 1, // 增加线条宽度，从1改为2
                    },
                  },
                ],
              },
            },
          ],
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              let result = `${params[0].name}<br/>`;
              params.forEach(function (item) {
                if (item.seriesIndex === 0) {
                  result += `${item.marker} ${item.seriesName}: ${item.value}元<br/>`;
                } else if (item.seriesIndex === 1) {
                  result += `${item.marker} ${item.seriesName}: ${item.value}%`;
                }
              });
              return result;
            },
          },
        });

        setTimeout(() => {
          chart.resize();
        }, 100);
      } else {
        chart.setOption({
          title: {
            // text: "各区县月均薪酬统计",
            // left: "center",
          },
          grid: {
            top: "8%",
            left: "5%",
            right: "5%",
            bottom: "10%",
            containLabel: true,
            borderWidth: 0, // 去掉网格边框
            show: false, // 隐藏网格背景
          },
          xAxis: {
            type: "category",
            data: ["全区县"],

            axisLabel: {
              rotate: 45,
              fontSize: 12,
              fontWeight: "normal",
              color: "#666666",
              fontFamily: "Arial, sans-serif",
              formatter: function (value) {
                return value;
              },
            },
          },
          yAxis: [
            {
              type: "value",
              name: "薪酬(元)",
            },
            {
              type: "value",
              name: "环比(%)",
              axisLine: {
                show: false, // 隐藏右侧Y轴线
              },
            },
          ],
          series: [
            {
              name: "平均薪酬",
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              type: "bar",

              itemStyle: {
                color: function (params) {
                  return params.dataIndex === 0 ? "#ff7f50" : "#91CC75";
                },
              },
              label: {
                show: true,
                position: "top",
                fontSize: 12,
                color: "#333",
                fontWeight: "normal",
                formatter: function (params) {
                  if (
                    params.value === 0 ||
                    params.value === null ||
                    params.value === undefined
                  ) {
                    return "";
                  }
                  return Math.round(params.value) + "元";
                },
              },
            },
          ],
          tooltip: {
            trigger: "axis",
          },
        });

        setTimeout(() => {
          chart.resize();
        }, 100);
      }

      chartRef._echarts_instance_ = chart;
    },
  },
};
</script>

<style scoped>
.wangge-chart {
  padding: 20px;
}
.wangge-chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
.wangge-chart-container {
  height: 400px;
}
</style>
